package com.flx.cloud.shop.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Fenglixiong
 * @Create 2022/5/3 0:01
 * @Description
 **/
@Configuration
public class MybatisPlusConfig {

    /**
     * 配置mybatis的配置项
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setCacheEnabled(false);
            //配置是否打印log日志，默认不打印
            configuration.setLogImpl(StdOutImpl.class);

        };
    }

    /**
     * 配置MybatisPlus的配置项
     * @return
     */
    @Bean
    public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
        return plusProperties -> {
            plusProperties.setMapperLocations(new String[]{"classpath:mapper/*.xml"});
            plusProperties.getGlobalConfig().getDbConfig().setIdType(IdType.AUTO);
        };
    }

    /**
     * 配置dao扫描方法
     * 其一，在配置文件上面添加@MapperScan("com.flx.dis.nacos.user.mapper")
     * 其二，扫描mybatis的dao层中含有注解@DaoMapper的类
     *
     * 配置扫描 com.flx.dao.package = ${value}
     * 默认扫描 com.flx.**.dao
     *
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.flx.**.mapper");
        return scannerConfigurer;
    }

    /**
     * 设置分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//避免每次分页都去抓取数据库类型
        //interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//注册乐观锁插件
        return interceptor;
    }

}
